//
//  ICMGetCarSearchViewController.m
//  ICrEAM
//
//  Created by kuroro on 16/11/1.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ICMGetCarSearchViewController.h"
#import "GetCarViewController.h"
#import "ICMGetCarSearchView.h"
#import "ICMHeaderView.h"
#import "GetCarPreviewControllerViewController.h"
#import "ICMPictureModel.h"
#import "ICMBasicInfoModel.h"
#import "ICMCarePackageDownModel.h"
#import "ICMCheckAppearanceDownModel.h"
#import "ICMPartsTopModel.h"
#import "ICMCarePackageModel.h"
#import "ICMActivityModel.h"
#import "ICMRepairMaintenanceModel.h"
#import "ICMRepairPartsModel.h"
#import "CustomRecordModel.h"
@interface ICMGetCarSearchViewController ()<ICMHeaderViewDelegate,ICMGetCarSearchViewDelegate,UITextFieldDelegate>{
    NSString *LABOUR_PRICE;
    NSMutableArray *LABOUR_PRICEarray;
}
@property (nonatomic, strong) ICMHeaderView *headerView;
@property (nonatomic, strong) ICMGetCarSearchView *ICMGetCarSearchView;
@property (nonatomic, strong) NSMutableArray *imageModels;
@end

@implementation ICMGetCarSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    __weak typeof(self) weakSelf = self;
    self.headerView = [ICMHeaderView createHeaderViewWithFrame:CGRectMake(ScreenWidth/8, 0, ScreenWidth-(ScreenWidth/8), ActualHeight(40)) andTitles:@[@"接车单查询"] andType:@"1"];
    self.headerView.delegate = self;
    [self.view addSubview:self.headerView];
    
    self.view.backgroundColor = BackgroundColor_HeaderBlue;
    self.ICMGetCarSearchView = [ICMGetCarSearchView creatICMGetCarSearchViewWithFrame:CGRectMake(0, ActualHeight(40), ScreenWidth, ScreenHeight-ActualHeight(40)-NavBarAndStatusHeight) dataArray:nil];
    self.ICMGetCarSearchView.delegate = self;
    [self.view addSubview:self.ICMGetCarSearchView];
    UIView *searchView = [[UIView alloc]init];
    searchView.backgroundColor = [UIColor whiteColor];
    searchView.layer.cornerRadius = ActualHeight(32)/2.0;
    UIImageView *searchImage = [[UIImageView alloc]init];
    searchImage.image = [UIImage imageNamed:GetCar_SearchIcon];
    [searchView addSubview:searchImage];
    [searchImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(searchView.mas_centerY);
        make.left.equalTo(searchView.mas_left).offset(5);
        make.height.equalTo(@(ActualWidth(28)));
        make.width.equalTo(@(ActualHeight(28)));
    }];
    
    
    UITextField * searchText = [[UITextField alloc]init];
    searchText.placeholder = @"车牌号，送修人姓名，送修人手机，服务顾问";
    searchText.returnKeyType = UIReturnKeySearch;
    searchText.delegate = self;
    searchText.font = [UIFont systemFontOfSize:14];
    [searchView addSubview:searchText];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:searchText];
    
    [searchText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(searchImage.mas_right);
        make.top.equalTo(searchView.mas_top);
        make.bottom.equalTo(searchView.mas_bottom);
        make.right.equalTo(searchView.mas_right).offset(-15);
    }];
    [self.view addSubview:searchView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.headerView.mas_right).offset(ActualWidth(-60));
        make.centerY.equalTo(weakSelf.headerView.mas_centerY);
        make.width.equalTo(@(ActualWidth(400)));
        make.height.equalTo(@(ActualHeight(32)));
        
    }];
    [self searchWithText:@"" type:@"0"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCarStatesHaveChanged) name:@"getCarStatesHaveChanged" object:nil];
    //[self.navigationController setNavigationBarHidden:NO animated:YES];
    
    
}

//默认支持大写
- (void)textFiledEditChanged:(NSNotification *)obj {
    UITextField *textField = obj.object;
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            textField.text= toBeString.uppercaseString;
        }else{
            // 有高亮选择的字符串
        }
    }else {
        textField.text = textField.text.uppercaseString;
    }
}

- (void)getCarStatesHaveChanged{
    [self searchWithText:@"" type:@"0"];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self searchWithText:textField.text type:@"1"];
    [textField resignFirstResponder];
    return YES;
}

- (void)headerViewDidSelectedButtonAtIndex:(NSInteger)index{
    
}

//接车单查询
- (void)searchWithText:(NSString *)text type:(NSString *)type{
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:text forKey:@"QUERY_CONDITION"];
    [parameters setObject:@(1) forKey:@"CURRENT_PAGE"];
    [manager startGetRequestWithURL:ReceptionVehicleOrder parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue] == 200) {
            NSMutableArray *searchArray = [NSMutableArray array];
            LABOUR_PRICEarray = [NSMutableArray array];
            if (IsArr(data[@"TT_RECEPTION_VEHICLE_ORDER"])) {
                NSArray *dataArray = data[@"TT_RECEPTION_VEHICLE_ORDER"];
                for (NSDictionary *searchData in dataArray) {
                    ICMGetCarSearchModel *model = [[ICMGetCarSearchModel alloc]init];
                    model.getCarId = searchData[@"RECEPTION_NO"];
                    model.licenceNumber = searchData[@"LICENSE"];
                    model.time = [searchData[@"CREATE_DATE"] stringValue];
                    model.vehicleType = searchData[@"SERIES_CODE"];
                    model.vehicleTypeName = searchData[@"SERIES_NAME"];
                    model.carModel = searchData[@"MODEL_CODE"];
                    ParameterModel *Pmodel = [ICrEAMTool getCodeModelForCode:[NSString stringWithFormat:@"%@",searchData[@"RECEPTION_STATUS"]]];
                    
                    
                    model.RECEPTION_STATUS = [NSString stringWithFormat:@"%@",searchData[@"RECEPTION_STATUS"]];
                    model.state = Pmodel.desc;
                    model.ownerName = searchData[@"DELIVERER"];
                    model.ownerMobile = searchData[@"DELIVERER_MOBILE"];
                    model.serverMobile = searchData[@"SERVICE_ADVISOR_MOBILE"];
                    model.serverName = searchData[@"SERVICE_ADVISOR_NAME"];
                    
                    [self getLABOUR_PRICE:model.carModel];
                    [searchArray addObject:model];
                }
            }
            self.ICMGetCarSearchView.condition = text;
            [self.ICMGetCarSearchView setModels:searchArray];
        }
    }];
}

#pragma mark 加载更多数据
- (void)loadMoreDataWithPage:(int)pageNo WithText:(NSString *)condition
{
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:condition forKey:@"QUERY_CONDITION"];
    [parameters setObject:@(pageNo) forKey:@"CURRENT_PAGE"];
    [manager startGetRequestWithURL:ReceptionVehicleOrder parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        [self.ICMGetCarSearchView loadMoreDataWithData:data];
    }];
}

- (void)didClickSearchViewWithRECEPTION_NO:(NSString *)RECEPTION_NO andIndex:(NSInteger )Index{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:RECEPTION_NO forKey:@"RECEPTION_NO"];
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    
    [manager startGetRequestWithURL:ReceptionVehicleOrderDetils parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue] == 200) {
            self.imageModels = [NSMutableArray array];
            if (IsArr(data[@"TT_RECPTION_DAMANGE"])) {
                NSArray *images = data[@"TT_RECPTION_DAMANGE"];
                for (NSDictionary *dic in images) {
                    ICMPictureModel *model = [ICMPictureModel yy_modelWithDictionary:dic];
                    [self.imageModels addObject:model];
                }
            }
            
            GetCarPreviewControllerViewController *GCP = [GetCarPreviewControllerViewController alloc];
//            GCP.SERIES_LABOUR_PRICE = LABOUR_PRICEarray[Index];
            if (IsArr(data[@"TT_RECEPTION_VEHICLE_ORDER"])) {
                ICMBasicInfoModel *infoModel = [ICMBasicInfoModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
                GCP.basicInfoModel = infoModel;
                
                
            }
            if (IsArr(data[@"TT_RECEPTION_VEHICLE_ORDER"])) {
                ICMCarePackageDownModel *carePackageDownModel = [ICMCarePackageDownModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
                GCP.carePackageDownModel = carePackageDownModel;
            }
            if (IsArr(data[@"TT_RECEPTION_VEHICLE_ORDER"])) {
                ICMCheckAppearanceDownModel *checkAppearanceDownModel = [ICMCheckAppearanceDownModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
                GCP.checkAppearanceDownModel = checkAppearanceDownModel;
            }
            
//                ICMPartsTopModel *partsTopModel = [ICMPartsTopModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
//                
//                partsTopModel.SERIES_LABOUR_PRICE = LABOUR_PRICEarray[Index];
//                partsTopModel.LABOUR_PRICE = LABOUR_PRICEarray[Index];
//                
//                GCP.partsTopModel = partsTopModel;
            if (IsArr(data[@"TT_RECEPTION_VEHICLE_ORDER"])) {
                ICMPartsTopModel *partsTopModel = [ICMPartsTopModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
//                partsTopModel.SERIES_LABOUR_PRICE = LABOUR_PRICEarray[Index];
                GCP.partsTopModel = partsTopModel;
            }

            
            ICMCarePackageModel *carePackageModel = [ICMCarePackageModel yy_modelWithDictionary:data];
            [carePackageModel createCarePackageItemModel];
            GCP.carePackageModel = carePackageModel;
            
            ICMRepairMaintenancesModel *repairMaintenanceModel = [ICMRepairMaintenancesModel yy_modelWithDictionary:data];
            [repairMaintenanceModel createRepairMaintenanceModel];
            
            ICMRepairPartsArrayModel *repairPartsModel = [ICMRepairPartsArrayModel yy_modelWithDictionary:data];
            [repairPartsModel createRepairPartsModel];
            
            ICMActivityModel *activityModel = [ICMActivityModel yy_modelWithDictionary:data];
            [activityModel createActivityItemModel];
            
            ICMCheckAppearanceTopModel *checkAppearanceTopModel = [ICMCheckAppearanceTopModel yy_modelWithDictionary:data];
            [checkAppearanceTopModel createPictureModel];
            
            GCP.repairEventModel = repairMaintenanceModel;
            GCP.repairPartsModel = repairPartsModel;
            GCP.activityModel = activityModel;
            GCP.checkAppearanceTopModel = checkAppearanceTopModel;
            [self.navigationController pushViewController:GCP animated:YES];
        
        }
    }];
    
}


//编辑
- (void)didClickCellWithSearchModel:(ICMGetCarSearchModel *)searchModel {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:searchModel.getCarId forKey:@"RECEPTION_NO"];
    
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    [manager startGetRequestWithURL:ReceptionVehicleOrderDetils parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue] == 200) {
            self.imageModels = [NSMutableArray array];
            NSArray *images = data[@"TT_RECPTION_DAMANGE"];
            if (IsArr(images)) {
                for (NSDictionary *dic in images) {
                    ICMPictureModel *model = [ICMPictureModel yy_modelWithDictionary:dic];
                    [self.imageModels addObject:model];
                }
            }
            
            GetCarViewController *GCVC = [GetCarViewController new];
            GCVC.isEditType = YES;
            
            //接车完成
            if ([searchModel.RECEPTION_STATUS isEqualToString:@"35521002"]) {
                GCVC.isIn = YES;
            } else {
                GCVC.isIn = NO;
            }
            if (IsArr(data[@"TT_RECEPTION_VEHICLE_ORDER"])) {
                ICMBasicInfoModel *infoModel = [ICMBasicInfoModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
                GCVC.basicInfoModel = infoModel;
                
                CustomRecordModel *record = [CustomRecordModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
                GCVC.editModel = record;
                
                if(IsStrEmpty(record.OWNER_NO)){
                    GCVC.isRetainer = NO;
                }
                
                
            }
            if (IsArr(data[@"TT_RECEPTION_VEHICLE_ORDER"])) {
                ICMCarePackageDownModel *carePackageDownModel = [ICMCarePackageDownModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
                GCVC.carePackageDownModel = carePackageDownModel;
            }
            if (IsArr(data[@"TT_RECEPTION_VEHICLE_ORDER"])) {
                ICMCheckAppearanceDownModel *checkAppearanceDownModel = [ICMCheckAppearanceDownModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
                GCVC.checkAppearanceDownModel = checkAppearanceDownModel;
            }
            if (IsArr(data[@"TT_RECEPTION_VEHICLE_ORDER"])) {
                ICMPartsTopModel *partsTopModel = [ICMPartsTopModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
                
                GCVC.partsTopModel = partsTopModel;
            }
            ICMCarePackageModel *carePackageModel = [ICMCarePackageModel yy_modelWithDictionary:data];
            [carePackageModel createCarePackageItemModel];
            GCVC.carePackageModel = carePackageModel;
            
            ICMRepairMaintenancesModel *repairMaintenanceModel = [ICMRepairMaintenancesModel yy_modelWithDictionary:data];
            [repairMaintenanceModel createRepairMaintenanceModel];
            
            ICMRepairPartsArrayModel *repairPartsModel = [ICMRepairPartsArrayModel yy_modelWithDictionary:data];
            [repairPartsModel createRepairPartsModel];
            
            ICMActivityModel *activityModel = [ICMActivityModel yy_modelWithDictionary:data];
            [activityModel createActivityItemModel];
            
            
            
            ICMCheckAppearanceTopModel *checkAppearanceTopModel = [ICMCheckAppearanceTopModel yy_modelWithDictionary:data];
            [checkAppearanceTopModel createPictureModel];
            GCVC.isSave = YES;
            GCVC.repairEventModel = repairMaintenanceModel;
            GCVC.repairPartsModel = repairPartsModel;
            GCVC.activityModel = activityModel;
            GCVC.checkAppearanceTopModel = checkAppearanceTopModel;
            GCVC.imageModels = self.imageModels;
            [self.navigationController pushViewController:GCVC animated:YES];
        }
    }];
}

//选择套餐需要的车型 工时
-(void)getLABOUR_PRICE:(NSString *)carModel{
    
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    if(IsStrEmpty(carModel)){
        carModel = @"";
    }
    [parameters setObject:carModel forKey:@"MODEL_CODE"];
    
    [manager startGetRequestWithURL:queryLabourPrice parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue] == 200) {
            
            LABOUR_PRICE = data[@"LABOUR_PRICE"];

        }
        [LABOUR_PRICEarray addObject:LABOUR_PRICE];
    }];
    
   
}
-(NSString *)calculateWorkingHoursWithSERIES_LABOUR_PRICE:(NSString *)SERIES_LABOUR_PRICE andREPAIR_ITEM_TYPE_RATE:(NSString *)REPAIR_ITEM_TYPE_RATE andTECHNIC_MODULUS:(NSString *)TECHNIC_MODULUS{
    
    double series_labour_price = [SERIES_LABOUR_PRICE floatValue];
    double repair_item_type_rate = [REPAIR_ITEM_TYPE_RATE floatValue];
    double texhnic_modulus = [TECHNIC_MODULUS floatValue];
    
    double workingHours = series_labour_price * repair_item_type_rate * texhnic_modulus;
    
    NSString *workingHoursStr = [NSString stringWithFormat:@"%.2f",workingHours];
    
    return workingHoursStr;
}


@end
